<?php
require_once APPLICATION_PATH . '/configs/saetv2.ex.class.php';

class Application_Model_UnionUser_weibo extends Application_Model_UnionUser_Base{
    
    const WB_AKEY = '3634022964';
    const WB_SKEY = 'a37714330d549f3ad5e5e0087501d709';
    const WB_CALLBACK_URL = 'http://www.uuch.com/user/unioncallback/name/weibo';
    
    protected $_token;

    public function getLoginUrl() {
        $url = 'https://api.weibo.com/oauth2/authorize?client_id=' . self::WB_AKEY . '&redirect_uri=' . self::WB_CALLBACK_URL;
        return $url;
    }
    
    public function getUnionName() {
        return '新浪微博';
    }
    
    public function getUserInfo() {
        $client = new SaeTClientV2(self::WB_AKEY, self::WB_SKEY, $this->_token['access_token']);
        $client->home_timeline(); // done
        $uid_get = $client->get_uid();
        $uid = $uid_get['uid'];
        $user_message = $client->show_user_by_id($uid); //根据ID获取用户等基本信息

        $result = new Application_Model_UnionUser_UserInfo();
        $result->nickname = $user_message['name'];
        $result->userKey = 'weibo'.$this->_token['uid'];
        return $result;
    }
    
    public function getUserKey() {
        return 'weibo'.$this->_token['uid'];
    }
   
    public function isValid() {
        $oauth = new SaeTOAuthV2(self::WB_AKEY, self::WB_SKEY);
        if (!isset($_REQUEST['code'])){
            return FALSE;
        }
        $keys = array();
        $keys['code'] = $_REQUEST['code'];
        $keys['redirect_uri'] = self::WB_CALLBACK_URL;
        $token = $oauth->getAccessToken('code', $keys);
        $this->_token = $token;
        return $token;
    }
}